package wxpay

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"server/global"
	"server/internal/pkg/wxpay_utility"
	"time"
)

func Transfer(TotalAmount int64, Openid, OutBatchNo string) (*TransferToUserResponse, error) {

	config, err := wxpay_utility.CreateMchConfig(
		global.GL_CONFIG.WxJsApi.MchID,                      // 商户号，是由微信支付系统生成并分配给每个商户的唯一标识符，商户号获取方式参考 https://pay.weixin.qq.com/doc/v3/merchant/4013070756
		global.GL_CONFIG.WxJsApi.MchCertificateSerialNumber, // 商户API证书序列号，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013053053
		"apiclient/apiclient_key.pem",                       // 商户API证书私钥文件路径，本地文件路径
		global.GL_CONFIG.WxJsApi.WechatpayPublicKeyID,       // 微信支付公钥ID，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013038816
		"apiclient/pub_key.pem",                             // 微信支付公钥文件路径，本地文件路径
	)
	if err != nil {
		return &TransferToUserResponse{}, err
	}

	request := &TransferToUserRequest{
		Appid:           wxpay_utility.String(global.GL_CONFIG.WxJsApi.Appid),
		OutBillNo:       wxpay_utility.String(OutBatchNo),
		TransferSceneId: wxpay_utility.String("1000"),
		Openid:          wxpay_utility.String(Openid),
		//UserName:           wxpay_utility.String("757b340b45ebef5467rter35gf464344v3542sdf4t6re4tb4f54ty45t4yyry45"), /*请传入 wxpay_utility.EncryptOAEPWithPublicKey 加密结果*/
		TransferAmount:     wxpay_utility.Int64(TotalAmount),
		TransferRemark:     wxpay_utility.String("观看直播奖励"),
		NotifyUrl:          wxpay_utility.String(global.GL_CONFIG.Server.DomainName + "/web_api/index/notice"),
		UserRecvPerception: wxpay_utility.String("现金奖励"),
		TransferSceneReportInfos: []TransferSceneReportInfo{
			{
				InfoType:    wxpay_utility.String("活动名称"),
				InfoContent: wxpay_utility.String("开直播领奖金"),
			},
			{
				InfoType:    wxpay_utility.String("奖励说明"),
				InfoContent: wxpay_utility.String("观看直播可领取奖励"),
			},
		},
	}
	response, err := TransferToUser(config, request)
	if err != nil {
		fmt.Printf("请求失败: %+v\n", err)
		return &TransferToUserResponse{}, err
	}
	//fmt.Printf("请求成功: %+v\n", response)
	return response, err

}

func TransferToUser(config *wxpay_utility.MchConfig, request *TransferToUserRequest) (response *TransferToUserResponse, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/fund-app/mch-transfer/transfer-bills"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqBody, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Accept", "application/json")
	httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
	httpRequest.Header.Set("Content-Type", "application/json")
	authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Authorization", authorization)

	client := &http.Client{}
	httpResponse, err := client.Do(httpRequest)
	if err != nil {
		return nil, err
	}
	respBody, err := wxpay_utility.ExtractResponseBody(httpResponse)
	if err != nil {
		return nil, err
	}
	if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
		// 2XX 成功，验证应答签名
		err = wxpay_utility.ValidateResponse(
			config.WechatPayPublicKeyId(),
			config.WechatPayPublicKey(),
			&httpResponse.Header,
			respBody,
		)
		if err != nil {
			return nil, err
		}
		response := &TransferToUserResponse{}
		if err := json.Unmarshal(respBody, response); err != nil {
			return nil, err
		}

		return response, nil
	} else {
		return nil, wxpay_utility.NewApiException(
			httpResponse.StatusCode,
			httpResponse.Header,
			respBody,
		)
	}
}

type TransferToUserRequest struct {
	Appid                    *string                   `json:"appid,omitempty"`
	OutBillNo                *string                   `json:"out_bill_no,omitempty"`
	TransferSceneId          *string                   `json:"transfer_scene_id,omitempty"`
	Openid                   *string                   `json:"openid,omitempty"`
	UserName                 *string                   `json:"user_name,omitempty"`
	TransferAmount           *int64                    `json:"transfer_amount,omitempty"`
	TransferRemark           *string                   `json:"transfer_remark,omitempty"`
	NotifyUrl                *string                   `json:"notify_url,omitempty"`
	UserRecvPerception       *string                   `json:"user_recv_perception,omitempty"`
	TransferSceneReportInfos []TransferSceneReportInfo `json:"transfer_scene_report_infos,omitempty"`
}

type TransferToUserResponse struct {
	OutBillNo      *string             `json:"out_bill_no,omitempty"`
	TransferBillNo *string             `json:"transfer_bill_no,omitempty"`
	CreateTime     *time.Time          `json:"create_time,omitempty"`
	State          *TransferBillStatus `json:"state,omitempty"`
	PackageInfo    *string             `json:"package_info,omitempty"`
}

type TransferSceneReportInfo struct {
	InfoType    *string `json:"info_type,omitempty"`
	InfoContent *string `json:"info_content,omitempty"`
}

type TransferBillStatus string

func (e TransferBillStatus) Ptr() *TransferBillStatus {
	return &e
}

const (
	TRANSFERBILLSTATUS_ACCEPTED          TransferBillStatus = "ACCEPTED"
	TRANSFERBILLSTATUS_PROCESSING        TransferBillStatus = "PROCESSING"
	TRANSFERBILLSTATUS_WAIT_USER_CONFIRM TransferBillStatus = "WAIT_USER_CONFIRM"
	TRANSFERBILLSTATUS_TRANSFERING       TransferBillStatus = "TRANSFERING"
	TRANSFERBILLSTATUS_SUCCESS           TransferBillStatus = "SUCCESS"
	TRANSFERBILLSTATUS_FAIL              TransferBillStatus = "FAIL"
	TRANSFERBILLSTATUS_CANCELING         TransferBillStatus = "CANCELING"
	TRANSFERBILLSTATUS_CANCELLED         TransferBillStatus = "CANCELLED"
)
